package com.cet.algorithm.贪心算法.K次取反后最大化的数组和;

import java.util.Arrays;
import java.util.stream.IntStream;

/**
 * @program: cet-practice
 * @description: K次取反后最大化的数组和
 * @author: 陈恩涛
 * @create: 2023-06-12 23:19
 **/
public class LC1005 {

    public int largestSumAfterKNegations2(int[] nums, int k) {
        // 将数组按照-num[i]排序
        for (int i = 0; i < nums.length; i++) {
            nums[i] = - nums[i];
        }

        Arrays.sort(nums);
        int result = 0;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (k > 0) {
                result += nums[i];
                k--;
            } else {
                result -= nums[i];
            }
        }
        return result;
    }

    public int largestSumAfterKNegations(int[] nums, int K) {
        // 将数组按照绝对值大小从大到小排序，注意要按照绝对值的大小
        nums = IntStream.of(nums)
            .boxed()
            .sorted((o1, o2) -> Math.abs(o2) - Math.abs(o1))
            .mapToInt(Integer::intValue).toArray();
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            //从前向后遍历，遇到负数将其变为正数，同时K--
            if (nums[i] < 0 && K > 0) {
                nums[i] = -nums[i];
                K--;
            }
        }
        // 如果K还大于0，那么反复转变数值最小的元素，将K用完

        if (K % 2 == 1) nums[len - 1] = -nums[len - 1];
        return Arrays.stream(nums).sum();

    }

    public static void main(String[] args) {
        LC1005 lc1005 = new LC1005();
        System.out.println(lc1005.largestSumAfterKNegations(new int[]{2, -3, -1, 5, -4}, 2));
    }
}
